package com.jplus.framework.util.serializer;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.framework.core.ConfigHandle;
import com.jplus.framework.util.serializer.impl.FSTSerializer;
import com.jplus.framework.util.serializer.impl.JavaSerializer;
import com.jplus.framework.util.serializer.impl.KryoPoolSerializer;
import com.jplus.framework.util.serializer.impl.KryoSerializer;

/**
 * 对象序列化工具包
 *
 * @author winterlau
 */
public class SerializationUtils {

	private final static Logger log = LoggerFactory.getLogger(SerializationUtils.class);
	private static Serializer g_ser;
 
	static {
		String ser = ConfigHandle.getString("app.serializer", "java");
		if (ser.equals("java")) {
			g_ser = new JavaSerializer();
		} else if (ser.equals("fst")) {
			g_ser = new FSTSerializer();
		} else if (ser.equals("kryo")) {
			g_ser = new KryoSerializer();
		} else if (ser.equals("kryo_pool_ser")) {
			g_ser = new KryoPoolSerializer();
		} else {
			try {
				g_ser = (Serializer) Class.forName(ser).newInstance();
			} catch (Exception e) {
				throw new RuntimeException("Cannot initialize Serializer named [" + ser + ']', e);
			}
		}
		log.info("Using Serializer -> [" + g_ser.name() + ":" + g_ser.getClass().getName() + ']');
	}

	public static byte[] serialize(Object obj) throws IOException {
		return g_ser.serialize(obj);
	}

	public static Object deserialize(byte[] bytes) throws IOException {
		return g_ser.deserialize(bytes);
	}

}
